package net.csdn.business.auth.authing;

import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.auth.service.CustomUserDetailsService;
import net.csdn.business.auth.utils.SecurityMessageSourceUtil;
import net.csdn.business.common.oauth2.component.AuthingAuthenticationToken;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;


/**
 * @Desc: 自定义authing登录Provider
 * @ClassName: AuthingAuthenticationProvider
 * @Author: yourleige@163.com
 * @Date: 2022/9/26 15:43
 */
@Slf4j
public class AuthingAuthenticationProvider implements AuthenticationProvider {

	private MessageSourceAccessor messages = SecurityMessageSourceUtil.getAccessor();


	@Getter
	@Setter
	private CustomUserDetailsService userDetailsService;

	@Override
	@SneakyThrows
	public Authentication authenticate(Authentication authentication) {
		AuthingAuthenticationToken authingAuthenticationToken = (AuthingAuthenticationToken) authentication;
		String principal = authingAuthenticationToken.getPrincipal().toString();
		UserDetails userDetails = userDetailsService.loadUserByAuthing(principal);
		if (userDetails == null) {
			log.debug("Authentication failed: no credentials provided");

			throw new BadCredentialsException(messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "Noop Bind Account"));
		}
		AuthingAuthenticationToken authenticationToken = new AuthingAuthenticationToken(userDetails,
				userDetails.getAuthorities());
		authenticationToken.setDetails(authingAuthenticationToken.getDetails());
		return authenticationToken;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return AuthingAuthenticationToken.class.isAssignableFrom(authentication);
	}

}
